//
//  HLComposeController.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/24.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLComposeController.h"
#import "HLUserAccountViewModel.h"
#import <Masonry.h>
#import "HLNetworking.h"
#import <SVProgressHUD.h>
#import "HLComposePictureController.h"

//底部toolBar的高度
#define ComposeToolBarHeight 35

@interface HLComposeController ()<UITextViewDelegate>
//写微博
@property (nonatomic,strong) UITextView *composeTextView;
//占位
@property (nonatomic,strong) UILabel *shareLabel;
//底部工具条
@property (nonatomic,strong) UIToolbar *composeToolBar;
//图片选择控制器
@property (nonatomic,strong) HLComposePictureController *composePictureVC;

@end

@implementation HLComposeController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏
    [self setupNav];
    //设置界面
    [self setupUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    //根据有没有图片来判断
    if (self.composePictureVC.composeImageArr == nil || self.composePictureVC.composeImageArr == 0) {
        //让textView成为第一响应者
        [self.composeTextView becomeFirstResponder];
    }
    
}


#pragma mark - 界面设置
//设置界面
- (void)setupUI {
    self.view.backgroundColor = [UIColor blueColor];
    //添加子控件
    //添加输入文本视图
    [self.view addSubview:self.composeTextView];
    //添加底部toolBar
    [self.view addSubview:self.composeToolBar];
    //设置约束
    [self.composeTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@(MainScreenHeight / 3));
    }];
    [self.composeToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@ComposeToolBarHeight);
    }];
    //设置文本输入视图
    [self setupComposeTextView];
    //设置图片选择器
    [self setupComposePictureView];
    //设置底部toolBar
    [self setupToolBar];
    //注册监听键盘
    [self registObbseverKeyBoard];
}

//注册监听键盘的弹出
- (void)registObbseverKeyBoard {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//设置底部toolBar
- (void)setupToolBar {
    //添加按钮
    NSMutableArray *arrM = [NSMutableArray array];
    //配置图片与方法的字典
    NSArray *arr =@[
                @{@"imageName":@"compose_toolbar_picture",@"didClickMethod":@"clickPictureBtn"},
                @{@"imageName":@"compose_mentionbutton_background"},
                @{@"imageName":@"compose_trendbutton_background"},
            @{@"imageName":@"compose_emoticonbutton_background",@"didClickMethod":@"clickEmoticonBtn"},
                @{@"imageName":@"compose_add_background"}
                ];
    //添加按钮
    for (NSDictionary *dic in arr) {
        //创建
        UIButton *btn = [[UIButton alloc] initWithImageName:dic[@"imageName"] withBackImageName:nil];
        if (dic[@"didClickMethod"]) {
            //点击响应事件
            [btn addTarget:self action:NSSelectorFromString(dic[@"didClickMethod"]) forControlEvents:UIControlEventTouchUpInside];
        }
        UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        //添加
        [arrM addObject:btnItem];
        //添加弹性按钮
        UIBarButtonItem *spaceBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [arrM addObject:spaceBtn];
    }
    //移除最后一个按钮
    [arrM removeLastObject];
    //将数组赋值给toolBar
    self.composeToolBar.items = arrM;
}

//设置图片选择器
- (void)setupComposePictureView {
    //创建控制器
    HLComposePictureController *composePictureVC = [[HLComposePictureController alloc] init];
    self.composePictureVC = composePictureVC;
    //添加图片选择控制器
    [self addChildViewController:composePictureVC];
    //添加视图
    [self.view addSubview:composePictureVC.view];
    //设置约束
    [composePictureVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.equalTo(@0);
    }];
    //将toolBar设置为图层最上层
    [self.view bringSubviewToFront:self.composeToolBar];
}

//设置文本输入视图
- (void)setupComposeTextView {
    [self.composeTextView addSubview:self.shareLabel];
    [self.shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.composeTextView).offset(8);
        make.left.equalTo(self.composeTextView).offset(5);
    }];
    //设置代理
    self.composeTextView.delegate = self;
}

//设置导航栏
- (void)setupNav {
    //关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(clickCloseBtn)];
    //发送按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(clickSendBtn)];
    //隐藏发送按钮
    self.navigationItem.rightBarButtonItem.enabled = NO;
    //title视图
    UIView *compaseTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 45)];
    //添加子控件
    UILabel *titleLabel = [[UILabel alloc] initWithTitle:@"发微博" withTitleFont:16 withTitleColor:[UIColor darkGrayColor]];
    UILabel *subTitleLabel = [[UILabel alloc] initWithTitle:[HLUserAccountViewModel getUserName] withTitleFont:12 withTitleColor:[UIColor lightGrayColor]];
    [compaseTitleView addSubview:titleLabel];
    [compaseTitleView addSubview:subTitleLabel];
    //设置自动布局
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.centerX.equalTo(compaseTitleView);
    }];
    [subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(compaseTitleView);
        make.top.equalTo(titleLabel.mas_bottom);
    }];
    //添加到导航条
    self.navigationItem.titleView = compaseTitleView;
}

#pragma mark - 键盘响应事件
- (void)keyBoardWillChange:(NSNotification *)noti {
    NSDictionary *info = noti.userInfo;
    //获取键盘结束时的frame
    CGRect endFrame = [info[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    //动画事件
    CGFloat duration = [info[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    //计算偏移量
    CGFloat offsetY = endFrame.origin.y - MainScreenHeight;
    //更新toolBar的约束
    [self.composeToolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(offsetY);
    }];
    //动画,立即更新约束
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - 导航栏按钮点击事件

//点击关闭按钮
- (void)clickCloseBtn {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//点击发送按钮
- (void)clickSendBtn {
    //设置参数
    NSDictionary *parameters = @{@"access_token":[HLUserAccountViewModel getUserToken], @"status": self.composeTextView.text};
    //根据有没有图片来判断请求方式
    if (self.composePictureVC.composeImageArr == nil || self.composePictureVC.composeImageArr.count == 0) {
        //发送请求
        [[HLNetworking sharedNetworing] sendHTTPRequestWithHTTPMethod:@"POST" withUrlStr:@"2/statuses/update.json" withParameters:parameters withFinshedBlock:^(id resultData, NSError *error) {
            if (error == nil) {
                [SVProgressHUD showSuccessWithStatus:@"发送成功"];
                [self clickCloseBtn];
            }else {
                [SVProgressHUD showErrorWithStatus:@"发送失败"];
            }
        }];
    }else {
        //有图片上传图片
        //获取图片二进制数据
        UIImage *image = self.composePictureVC.composeImageArr.firstObject;
        NSData *imageData = UIImagePNGRepresentation(image);
        //发送请求
        [[HLNetworking sharedNetworing] uploadImageDataWithUrlStr:@"https://upload.api.weibo.com/2/statuses/upload.json" withParameters:parameters withImageData:imageData withFinshBlock:^(id resultData, NSError *error) {
            if (error == nil) {
                [SVProgressHUD showSuccessWithStatus:@"发送成功"];
                [self clickCloseBtn];
            }else {
                [SVProgressHUD showErrorWithStatus:@"发送失败"];
            }
        }];
    }
    
}

#pragma mark - 底部toolBar响应事件
//点击图片按钮
- (void)clickPictureBtn {
    //更新约束
    [self.composePictureVC.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(MainScreenHeight * 2 / 3));
    }];
    //动画
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

//点击表情按钮
- (void)clickEmoticonBtn {
    NSLog(@"%s",__func__);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 代理方法
- (void)textViewDidChange:(UITextView *)textView {
    //根据有没有文本内容修改
    self.navigationItem.rightBarButtonItem.enabled = self.composeTextView.hasText;
    self.shareLabel.hidden = self.composeTextView.hasText;
}

#pragma mark - 懒加载子控件
- (UITextView *)composeTextView {
    if (_composeTextView == nil) {
        _composeTextView = [[UITextView alloc] init];
        //设置文字大小
        _composeTextView.font = [UIFont systemFontOfSize:14];
        //设置文字颜色
        _composeTextView.textColor = [UIColor darkGrayColor];
        //设置允许滚动
        _composeTextView.alwaysBounceVertical = YES;
        //设置滚动的时候隐藏键盘
        _composeTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _composeTextView;
}

//占位视图
- (UILabel *)shareLabel {
    if (_shareLabel == nil) {
        _shareLabel = [[UILabel alloc] initWithTitle:@"分享新鲜事" withTitleFont:14 withTitleColor:[UIColor lightGrayColor]];
    }
    return _shareLabel;
}

//底部站位视图
- (UIToolbar *)composeToolBar {
    if (_composeToolBar == nil) {
        _composeToolBar = [[UIToolbar alloc] init];
    }
    return _composeToolBar;
}

@end
